﻿using System;
using System.Configuration;
using System.Globalization;
using System.Web.Configuration;

namespace Salient.Web.Administration.AppConfig
{
    public partial class AppConfigHome : ApplicationConfigurationPage
    {
        public void Page_Load()
        {
            if (!IsPostBack)
            {
                string appPath = ApplicationPath;
                if (!String.IsNullOrEmpty(appPath))
                {
                    AppConfigTitle.Text = String.Format((string) GetLocalResourceObject("TitleForSite"), appPath);
                }

                System.Configuration.Configuration config = OpenWebConfiguration(appPath);
                var appSettingsSection = (AppSettingsSection) config.GetSection("appSettings");
                string numOfAppSettings = appSettingsSection.Settings.Count.ToString(CultureInfo.InvariantCulture);
                NumOfAppSettings.Text = String.Format((string) GetLocalResourceObject("NumOfAppSettings"),
                                                      numOfAppSettings);
            }
            UpdateApplicationOnlineUI();
        }

        public void ToggleApplicationOnline(object sender, EventArgs e)
        {
            System.Configuration.Configuration config = OpenWebConfiguration(ApplicationPath);
            var httpRuntimeSection = (HttpRuntimeSection) config.GetSection("system.web/httpRuntime");
            bool httpRuntimeSectionEnabled = httpRuntimeSection.Enable;

            httpRuntimeSection.Enable = !httpRuntimeSectionEnabled;
            SaveConfig(config);

            UpdateApplicationOnlineUI();
        }

        public void UpdateApplicationOnlineUI()
        {
            System.Configuration.Configuration config = OpenWebConfiguration(ApplicationPath);
            var httpRuntimeSection = (HttpRuntimeSection) config.GetSection("system.web/httpRuntime");

            if (httpRuntimeSection.Enable)
            {
                applicationOnlineState.Text = (string) GetLocalResourceObject("ApplicationStateOnline");
                toggleApplication.Text = (string) GetLocalResourceObject("TakeApplicationOffline");
            }
            else
            {
                applicationOnlineState.Text = (string) GetLocalResourceObject("ApplicationStateOffline");
                toggleApplication.Text = (string) GetLocalResourceObject("TakeApplicationOnline");
            }
        }
    }
}